<template>
    <div>
        <t-row :gutter="[24, 24]">
            <t-col :flex="3">
                <div class="user-left-greeting">
                    <div>
                        Hi，{{ userStore.userInfo?.nickName }}

                        <span class="regular">
                            {{ getTimeOfDay() }}, 今天你已经使用了第{{
                                Math.floor(
                                    (new Date() - new Date(userStore.userInfo?.createTime)) / (1000 * 60 * 60 * 24),
                                )
                            }}天了
                        </span>
                    </div>
                    <div>
                        <t-avatar size="45px" :image="userStore.userInfo?.avatar" style="margin-right: 50px" />
                    </div>
                </div>
                <t-card class="user-info-list" :title="t('pages.user.personalInfo.title')" :bordered="false">
                    <template #actions>
                        <t-button theme="default" shape="square" variant="text" @click="updateUser()">
                            <t-icon name="ellipsis" />
                        </t-button>
                    </template>
                    <t-descriptions :column="4" item-layout="vertical">
                        <t-descriptions-item label="用户名">
                            {{ userStore.userInfo?.userName }}
                        </t-descriptions-item>
                        <t-descriptions-item label="昵称">
                            {{ userStore.userInfo?.nickName }}
                        </t-descriptions-item>
                        <t-descriptions-item label="邮箱">
                            {{ userStore.userInfo?.email }}
                        </t-descriptions-item>
                        <t-descriptions-item label="手机号">
                            {{ userStore.userInfo?.phone }}
                        </t-descriptions-item>
                        <t-descriptions-item label="性别">
                            {{ userStore.userInfo?.sex === '1' ? '男' : '女' }}
                        </t-descriptions-item>
                        <t-descriptions-item label="部门ID">
                            {{ userStore.userInfo?.deptId || '无' }}
                        </t-descriptions-item>
                        <t-descriptions-item label="状态">
                            {{ userStore.userInfo?.status === 0 ? '启用' : '禁用' }}
                        </t-descriptions-item>
                        <t-descriptions-item label="最后登录IP">
                            {{ userStore.userInfo?.loginIp }}
                        </t-descriptions-item>
                        <t-descriptions-item label="最后登录时间">
                            {{ userStore.userInfo?.loginDate }}
                        </t-descriptions-item>
                        <t-descriptions-item label="创建时间">
                            {{ new Date(userStore.userInfo?.createTime).toLocaleString() }}
                        </t-descriptions-item>
                        <t-descriptions-item label="账号角色">
                            {{ userStore.userInfo?.roleName.join(', ') }}
                        </t-descriptions-item>
                    </t-descriptions>
                </t-card>
            </t-col>
        </t-row>

        <div>
            <!-- 修改用户弹出框 -->
            <t-dialog
                v-model:visible="updateDialogVisible"
                width="55%"
                header="修改新用户"
                placement="center"
                :on-cancel="onCancelUpdate"
                @confirm="onConfirmUpdate"
            >
                <t-form ref="createForm" :data="updateUserFormData" :label-width="80" colon>
                    <t-row :gutter="[0, 16]">
                        <t-col :span="5">
                            <t-form-item label="头像" name="avatar">
                                <div class="avatar-preview">
                                    <t-image
                                        :src="updateUserFormData.avatar"
                                        :style="{ width: '110px', height: '110px' }"
                                        style="margin-right: 50px"
                                    />
                                </div>
                                <t-upload
                                    ref="uploadRef"
                                    action="http://localhost:8081/api/file/upload"
                                    :multiple="multiple"
                                    :headers="upload.headers"
                                    :size-limit="{ size: 10, unit: 'MB' }"
                                    :max="1"
                                    :allow-upload-duplicate-file="true"
                                    :theme="'image'"
                                    accept="image/jpeg, image/png"
                                    :show-thumbnail="false"
                                    :show-image-file-name="false"
                                    class="upload_image"
                                    @fail="handleFail"
                                    @success="handleSuccess"
                                    @one-file-success="onOneFileSuccess"
                                    @remove="deleteImg"
                                />
                            </t-form-item>
                            <t-form-item label="账号名" name="userName">
                                <t-input v-model="updateUserFormData.userName" placeholder="请输入账户名" />
                            </t-form-item>
                            <t-form-item label="用户昵称" name="nickName">
                                <t-input v-model="updateUserFormData.nickName" placeholder="请输入用户昵称" />
                            </t-form-item>
                            <t-form-item label="密码" name="password">
                                <t-input v-model="updateUserFormData.password" placeholder="请输入用户密码" />
                            </t-form-item>
                        </t-col>
                        <t-col :span="1"></t-col>
                        <t-col :span="5">
                            <t-form-item label="手机号" name="phone">
                                <t-input v-model="updateUserFormData.phone" placeholder="请输入手机号" />
                            </t-form-item>
                            <t-form-item label="邮箱" name="email">
                                <t-input v-model="updateUserFormData.email" placeholder="请输入邮箱" />
                            </t-form-item>
                            <t-form-item label="账号状态" name="status">
                                <t-select
                                    v-model="updateUserFormData.status"
                                    :options="CONTRACT_STATUS_OPTIONS"
                                    placeholder="请选择账户状态"
                                />
                            </t-form-item>
                            <t-form-item label="性别" name="sex">
                                <t-select v-model="updateUserFormData.sex" :options="sexs" placeholder="请选择性别" />
                            </t-form-item>
                        </t-col>
                    </t-row>
                </t-form>
            </t-dialog>
        </div>
    </div>
</template>
<script lang="ts">
export default {
    name: 'UserIndex',
};
</script>
<script setup lang="ts">
import { LineChart } from 'echarts/charts';
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { t } from '@/locales';
import { useSettingStore, useUserStore } from '@/store';
import { getPermissionList, getUserById, updateUserById } from '@/api/user';
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, reactive, ref } from 'vue';

//初始化
onMounted(() => {
    init();
});

echarts.use([GridComponent, TooltipComponent, LineChart, CanvasRenderer, LegendComponent]);

const userStore = useUserStore();
const getTimeOfDay = () => {
    const now = new Date();
    const hours = now.getHours();

    if (hours >= 0 && hours < 6) {
        return '凌晨好，这么晚还不睡觉吗？';
    } else if (hours >= 6 && hours < 12) {
        return '早上好，今天又是元气满满的一天';
    } else if (hours >= 12 && hours < 18) {
        return '下午好，喝杯咖啡提提神吧';
    } else {
        return '晚上好，早点休息吧';
    }
};
const CONTRACT_STATUS_OPTIONS = [
    { value: 0, label: '正常' },
    { value: 1, label: '封禁' },
];
const sexs = [
    { value: 0, label: '男' },
    { value: 1, label: '女' },
];
const permissionStore = ref();
const init = async () => {
    // 初始化权限列表
    permissionStore.value = await getPermissionList();
};
// 修改
// 修改用户
const updateUser = async () => {
    try {
        updateDialogVisible.value = true;
        // 根据id查询修改用户的信息
        const response = await getUserById(userStore.userInfo.userId);
        console.log('response', response);
        updateUserFormData.value = {
            ...response,
            roleId: response.roleId || [],
            roleName: response.roleName || '',
        };
        console.log('updateUserFormData', updateUserFormData.value);
        updateDialogVisible.value = true;
    } catch (error) {
        console.error('获取用户信息失败:', error);
        MessagePlugin.error('获取用户信息失败');
    }
};
// 弹出框显示状态修改
const updateDialogVisible = ref(false);
// 修改用户的表单数据
const updateUserFormData = ref({
    id: '',
    avatar: '',
    userName: '',
    nickName: '',
    status: 0,
    phone: '',
    email: '',
    sex: 0,
    password: '',
    roleId: [],
});
// 取消修改用户
const onCancelUpdate = () => {
    updateDialogVisible.value = false;
    // 清空表单数据
    updateUserFormData.value = {
        avatar: '',
        email: '',
        id: '',
        nickName: '',
        password: '',
        phone: '',
        roleId: [],
        sex: 0,
        status: 0,
        userName: '',
    };
    // 清空图片上传列表
    resetUpload();
};

// 确认修改用户
const onConfirmUpdate = async () => {
    try {
        await updateUserById(updateUserFormData.value);
        // 重新获取用户信息
        await userStore.getUserInfo();
        updateDialogVisible.value = false;
        MessagePlugin.success('用户修改成功');
    } catch (error) {
        console.error('修改用户失败:', error);
        MessagePlugin.error('修改用户失败');
    } finally {
        // 清空表单数据
        onCancelUpdate();
        updateDialogVisible.value = false;
        resetUpload();
    }
};

// 图片上传
const { token } = userStore;

const upload = reactive({
    actionUrl: `http://localhost:8081/api/file/upload`,
    headers: {
        Authorization: token,
    },
});

const multiple = ref(false);
const uploadRef = ref(null);

const handleFail = (context: any) => {
    console.log('Upload failed:', context);
};
// 文件上传完成
const handleSuccess = (context: any) => {
    console.log('Upload success Url:', context.response.data);
    updateUserFormData.value.avatar = context.response.data;
};

const onOneFileSuccess = (context: any) => {
    console.log('One file upload success:', context);
};

const deleteImg = (context: any) => {
    console.log('Delete image:', context);
};

const resetUpload = () => {};

// 创建文件上传完成
const handleCreateSuccess = (context: any) => {
    console.log('Create success Url:', context.response.data);
    newUserFormData.value.avatar = context.response.data;
};
</script>

<style lang="less" scoped>
@import './index.less';

.t-descriptions {
    margin-top: 24px;
}

.avatar-container {
    display: flex;
    justify-content: center;
    margin-top: 16px;
}

.custom-avatar {
    width: 100px; /* 设置头像宽度 */
    height: 100px; /* 设置头像高度 */
    border-radius: 50%; /* 使头像变成圆形 */
    border: 2px solid #ccc; /* 添加边框 */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}
</style>
